//
//  RegisterViewController.m
//  wtshoppingcite
//
//  Created by TW on 14-10-21.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegisterStepOneView.h"
#import "RegisterStepTwoView.h"
#import "RegisterStepThreeView.h"
#import "ServiceTermsViewController.h"
#import "AppDelegate.h"
#import "RegisterHelper.h"
#import "CitesViewController.h"
#import "UIDevice+category.h"

@interface RegisterViewController ()<RegisterStepOneDelegate,
                                        StepThreeDelegate>

@property (nonatomic, strong) NSMutableData *receiveData;
@property(nonatomic,strong)UIImageView *stepImageView;
@property(nonatomic,strong) UIScrollView *registerScrollView;
@property(nonatomic,strong) RegisterStepThreeView *rgThreeView;
@property(nonatomic,strong)NSMutableArray *data;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setHidden:NO];
    
    
    _data = [[NSMutableArray alloc]initWithCapacity:1];
    
//    //处理导航条遮挡
//    if(Version>=7.0)
//    {
//        self.edgesForExtendedLayout = UIRectEdgeNone;
//        self.extendedLayoutIncludesOpaqueBars = NO;
//        self.modalPresentationCapturesStatusBarAppearance = NO;
//    }
    
    [self setTitleView:@"注册"];
    _stepImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, kWidth, 44)];
    _stepImageView.image = [UIImage imageNamed:@"registerStep_1"];
    [self.view addSubview:_stepImageView];
    self.registerScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, _stepImageView.bottom+5, kWidth, kHeight-118)];
    self.registerScrollView.contentSize = CGSizeMake(kWidth*3, kHeight-130);
    self.registerScrollView.pagingEnabled = YES;
    self.registerScrollView.showsVerticalScrollIndicator = NO;
    self.registerScrollView.showsHorizontalScrollIndicator = NO;
    self.registerScrollView.scrollEnabled = NO;
    [self.registerScrollView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:self.registerScrollView];
    
    [self initRegisterUI];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


-(void)initRegisterUI{
    
    RegisterStepOneView *rgOneView = [[[NSBundle mainBundle] loadNibNamed:@"RegisterStepOneView"
                                                                    owner:self
                                                                  options:nil]
                                      objectAtIndex:0];

    RegisterStepTwoView *rgTwoView = [[[NSBundle mainBundle] loadNibNamed:@"RegisterStepTwoView"
                                                                    owner:self
                                                                  options:nil]
                                      objectAtIndex:0];
    _rgThreeView = [[[NSBundle mainBundle] loadNibNamed:@"RegisterStepThreeView"
                                                                        owner:self
                                                                      options:nil]
                                          objectAtIndex:0];
    
  
    rgOneView.frame = CGRectMake(0, 0, DEVICE_WIDTH, rgOneView.height);
    rgOneView.delegate = self;                              
    rgOneView.stepBlock = ^(StepType type){
        [self setStepType:type];
        [rgTwoView setNeedsLayout];
    };
    [self.registerScrollView addSubview:rgOneView];
    
    
    rgTwoView.frame = CGRectMake(DEVICE_WIDTH, 0, DEVICE_WIDTH, rgOneView.height);
    rgTwoView.stepBlock = ^(StepType type){
        [self setStepType:type];
    };
    
    
    [self.registerScrollView addSubview:rgTwoView];
    
    _rgThreeView.frame = CGRectMake(DEVICE_WIDTH*2, 0, DEVICE_WIDTH, rgOneView.height);
    _rgThreeView.delegate = self;
    _rgThreeView.stepBlock = ^(StepType type){
        [self setStepType:type];
    };
    [self.registerScrollView addSubview:_rgThreeView];

}

- (void)setStepType:(StepType)type
{
    if(type == StepTypeTwo){
        self.stepImageView.image = [UIImage imageNamed:@"registerStep_2.png"];
        [self.registerScrollView setContentOffset:CGPointMake(DEVICE_WIDTH, 0) animated:YES];
    }
    else if(type == StepTypeThree){
        self.stepImageView.image = [UIImage imageNamed:@"registerStep_3.png"];
        [self.registerScrollView setContentOffset:CGPointMake(DEVICE_WIDTH*2, 0) animated:YES];
    }
    else if(type == StepTypeServiceTerm){
        [self performSegueWithIdentifier:@"ServiceTerms" sender:self];
    }
    else if(type == StepTypeFinish){
        [self performSegueWithIdentifier:@"PieriodView" sender:self];
    }
    
}

#pragma mark RegisterStepOneDelegate
-(void)pushView{
    
    ServiceTermsViewController *serviceTVC = [[ServiceTermsViewController alloc]init];
    [self.navigationController pushViewController:serviceTVC animated:YES];
    
}

-(void)getVerificationCode{
    
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    self.phone = [RegisterHelper shareHelper].registerPhoneNum;
    [paramDic setValue:self.phone forKey:@"tel"];
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                                andAPISuffix:kIdentifyCode
                               andHttpMethod:@"POST"
                               andParameters:paramDic
                             andRequestCache:NO
                              andUseParamDic:YES
                            andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                       andRequestFinishBlock:^(BYRequest *request, BYResponse *response)
     {
         
         if(!response.isError){
             NSDictionary *responseDic = request.responseJSON;
             DLog(@"获取验证码  %@",responseDic);
             
         }
         else{
             
             DLog(@"获取验证码失败  %@",response.errorMessage);
         }
     }];
    


}


#pragma mark StepThreeDelegate
-(void)confirmAction{
    
    __weak RegisterViewController *weak_self = self;
    
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    
    self.phone = [RegisterHelper shareHelper].registerPhoneNum;
    NSString *phone = self.phone;
    NSString *pwd = [[[RegisterHelper shareHelper]password] md5];
    NSString *verifyCode = [[RegisterHelper shareHelper]verifyCode];
    NSString *str = BUNDLE_VERSION;
    
    int vcodeSr = [str intValue];
    NSString *vcode = [NSString stringWithFormat:@"%d",vcodeSr];
    NSString *cid = [[RegisterHelper shareHelper]citesId];
    NSString * uniqueId = [[UIDevice currentDevice] getDeviceUniqueID];
    NSNumber *pm = @1;
    NSString *appCode = @"1001";
    
    [paramDic setValue:phone forKey:@"tel"];
    [paramDic setValue:pwd forKey:@"psd"];
    [paramDic setValue:verifyCode forKey:@"mcode"];
    [paramDic setValue:vcode forKey:@"vcode"];
    [paramDic setValue:cid forKey:@"cid"];
    [paramDic setValue:uniqueId forKey:@"did"];
    [paramDic setValue:pm forKey:@"pm"];
    [paramDic setValue:appCode forKey:@"appCode"];
    [paramDic setValue:[RegisterHelper shareHelper].nickName forKey:@"nickName"];
    [paramDic setValue:[RegisterHelper shareHelper].invitCode forKey:@"registerInviteCode"];
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kRegister
                             andHttpMethod:@"POST"
                             andParameters:paramDic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response){
                         
                         if(!response.isError){
                             NSDictionary *responseDic = request.responseJSON;
                             NSString *msg = [responseDic objectForKey:@"msg"];
                             NSLog(@"%@",msg);
                             DLog(@"获取参数  %@",responseDic);
                             
                             BOOL result= [[responseDic objectForKey:@"result"]boolValue];
                             
                             if (!result) {
                                 
                            [self showToastWithMessage:@"恭喜您，注册成功!" showTime:3];
                                 
//                             [APP_DELEGATE pushLoginViewControllerWithStoryBoardIdentifier:@"MainViewController" pushIn:self];
                                 
                                 //注册完登录
                                 [self loginMethodWithParams];
                                 
                             }else{
                                 
                                 DLog(@"登录失败 %@",responseDic);
//                                 weak_self.hud.labelText = [responseDic objectForKey:@"msg"];
//                                 [weak_self.hud hide:YES afterDelay:1];
                                 [self showToastMessage:[responseDic objectForKey:@"msg"]];
                             }
                         }
                         else{
                             
                             DLog(@"获取参数失败  %@",response.errorMessage);
//                             [self showToastMessage:@"登录失败"];
                         }
                     }];
    
}


////注册完调登录接口
- (void)loginMethodWithParams{
    
    
    NSString *password = [[[RegisterHelper shareHelper]password] md5];
    NSString *vcode = BUNDLE_VERSION;
    NSInteger c = vcode.integerValue;
    vcode = [NSString stringWithFormat:@"%ld",(long)c];
    NSNumber *pm = @1;
    NSString *appCode = @"1001";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    SetValueForKey(params, [RegisterHelper shareHelper].registerPhoneNum, @"tel");
    SetValueForKey(params,password, @"psd");
    SetValueForKey(params, vcode, @"vcode");
    SetValueForKey(params, pm, @"pm");
    SetValueForKey(params, appCode, @"appCode");
    
    
//    __weak LoginViewController *weak_self = self;
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kLogin
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         if(!response.isError){
                             NSDictionary *responseDic = request.responseJSON;
                             NSString *msg = [responseDic objectForKey:@"msg"];
                             NSLog(@"%@",msg);
                             DLog(@"获取参数  %@",responseDic);
                             
                             BOOL result= [[responseDic objectForKey:@"result"]boolValue];
                             
                             if (!result) {
                                 
                                 NSArray *list = [responseDic objectForKey:@"prodcutType"];
                                 
                                 [RegisterHelper shareHelper].score = [responseDic objectForKey:@"score"];
                                 [RegisterHelper shareHelper].userId = [responseDic objectForKey:@"userId"];
                                 [RegisterHelper shareHelper].citesName = [responseDic objectForKey:@"comnityName"];
                                 [RegisterHelper shareHelper].citesId = [responseDic objectForKey:@"comnityId"];
                                 [RegisterHelper shareHelper].registerPhoneNum = self.phone;
                                 
                                 for (NSDictionary *dic in list) {
                                     CustomerModel *customerModel = [[CustomerModel alloc]initWithCustomerInfo:dic];
                                     [_data addObject:customerModel];
                                 }
                                 [RegisterHelper shareHelper].productArray = _data;
                                 [self gotoAppDelgate:responseDic];
                                 [[NSUserDefaults standardUserDefaults] setObject:self.phone forKey:@"usersPhoneNum"];
                                 [[NSUserDefaults standardUserDefaults] synchronize];
                                 
                                 [[NSUserDefaults standardUserDefaults] setObject:self.password forKey:@"usersPassword"];
                                 [[NSUserDefaults standardUserDefaults] synchronize];
                                 
                             }else{
                                 
                                 DLog(@"登录失败 %@",responseDic);
                                 
                                 [self showToastMessage:[responseDic objectForKey:@"msg"]];
                                 
                             }
                         }
                         else{
                             
                             [self showToastMessage:response.errorMessage];
                         }
                     }];
}

//注册完登录
-(void)gotoAppDelgate:(NSDictionary *)userModel{
    
    [[AppDelegate sharedDelegate] initCustomerModel:userModel];
    //    [self dismissViewControllerAnimated:YES completion:nil];
    [APP_DELEGATE initMainViewControllerWithStoryBoardIdentifier:@"MainViewController" type:0 pushIn:self];
    
}


//省
-(void)selectProvinceAction{
    
}

//市
-(void)selectCitesAction{
    
    CitesViewController *citesVC = [[CitesViewController alloc]init];
//    [citesVC startRequestDataWithCode:@"440300"];
    citesVC.isRegister = YES;
    [self.navigationController pushViewController:citesVC animated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [_rgThreeView.citesButton setTitle:[RegisterHelper shareHelper].citesName forState:UIControlStateNormal];
}
@end
